package com.mlz.mlzmall.ui.activity.act.personal.userLogin;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.mlz.mlzmall.R;
import com.mlz.mlzmall.custom.circleimageview.CircleImageView;
import com.mlz.mlzmall.ui.activity.act.personal.NetworkRequest.VolleyBaseActivity;
import com.mlz.mlzmall.ui.utils.mlz.URL;
import com.mlz.mlzmall.ui.utils.util.ACache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;

/**
 * @description 关联帐号
 * Created by 安帅 on 2016/5/31 16:21.
 * PackageName com.mlz.mlzmall.ui.activity.act.personal.userLogin.
 * ProjectName mlzmall_android.
 */
public class RelationPhoneActivity extends VolleyBaseActivity implements View.OnClickListener {
    private static final String TGA = "RelationPhoneActivity";
    //用户头像
    CircleImageView imPhotoRelation;
    //用户名
    TextView tvNameRelation;
    //关联手机号
    EditText et_phoneRelation;
    // 获取验证码
    Button btn_getVerifyCode_Relation;
    //输入验证码
    EditText et_InputVerifyCodeRelation;
    //输入的密码
    EditText et_passwordRelation;
    // 确认关联
    Button btnConfirmRelative;
    // 获取个人信息
    PostLoginOauth resposeGetPersonInfo;
    private DisplayImageOptions options;    // 用于下载网路图片、定义参数
    private ImageLoader imageLoader = ImageLoader.getInstance();    // 新建静态实例对象
    // 用户判断用户有没有注册
    int unRegeisted = -100;
    private RestTemplate restTemplate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_relation_phone);
        Intent intent = getIntent();
        if (intent.getAction().equals("WEIBO_BINDER")) {
            resposeGetPersonInfo = new PostLoginOauth();
            resposeGetPersonInfo.setType(intent.getExtras().getString("type"));
            resposeGetPersonInfo.setName(intent.getExtras().getString("username"));
            resposeGetPersonInfo.setAvatar(intent.getExtras().getString("image"));
            resposeGetPersonInfo.setLoginId(intent.getExtras().getString("id"));
            resposeGetPersonInfo.setAddress(intent.getExtras().getString("address"));
            resposeGetPersonInfo.setGender(intent.getExtras().getInt("gender"));
        }

        restTemplate = new RestTemplate();
        new HttpUtlis(RelationPhoneActivity.this).saveSessionKey(restTemplate);

        // 获取绑定用到个人信息
        GetPersonInfo();
        // 初始化控件
        initView();
    }

    //获取绑定用到个人信息
    private void GetPersonInfo() {
        if ("FROM_LOGIN_ACTIVITY_TO_BUILDING".equals(this.getIntent().getAction())) {
            ArrayList array = this.getIntent().getCharSequenceArrayListExtra("data");
            resposeGetPersonInfo = (PostLoginOauth) array.get(0);
        }
    }

    // 初始化控件
    private void initView() {
        imPhotoRelation = (CircleImageView) findViewById(R.id.imPhotoRelation);
        tvNameRelation = (TextView) findViewById(R.id.tvNameRelation);
        et_phoneRelation = (EditText) findViewById(R.id.et_phoneRelation);
        btn_getVerifyCode_Relation = (Button) findViewById(R.id.btn_getVerifyCode_Relation);
        et_InputVerifyCodeRelation = (EditText) findViewById(R.id.et_InputVerifyCodeRelation);
        et_passwordRelation = (EditText) findViewById(R.id.et_passwordRelation);
        btnConfirmRelative = (Button) findViewById(R.id.btnConfirmRelative);

        ImageLoader.getInstance().displayImage(resposeGetPersonInfo.getAvatar(), imPhotoRelation);
        // 设置姓名
        tvNameRelation.setText(resposeGetPersonInfo.getName());
        btnConfirmRelative.setOnClickListener(this);
    }


    // 设置监听
    public void onClick(View v) {
        switch (v.getId()) {
            // 获取输入的手机号,获取验证码
            case R.id.btn_getVerifyCode_Relation:
                String phone = et_phoneRelation.getText().toString().trim();
                if (!phone.isEmpty() && !"".equals(phone)) {
                    getVerifyCodeForLogin(phone);
                    MyCountTimer timeCount = new MyCountTimer(btn_getVerifyCode_Relation, 0xfff30008, 0xff969696);
                    timeCount.start();
                } else {
                    Toast.makeText(getBaseContext(), "手机号码为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                break;
            // 确认关联
            case R.id.btnConfirmRelative:
                Log.i(TGA, "点击了、、、、、");
                // 手机号
                phone = et_phoneRelation.getText().toString().trim();
                // 验证码
                String sms = et_InputVerifyCodeRelation.getText().toString().trim();
                // 密码
                String password = et_passwordRelation.getText().toString().trim();
                // DeviceId
                TelephonyManager telephonyManager = (TelephonyManager) RelationPhoneActivity.this.getSystemService(Context.TELEPHONY_SERVICE);
                String DeviceId = telephonyManager.getDeviceId().toString();
                // 如果用户不存,先注册
                if (unRegeisted == 1107) {
                    Log.i(TGA, "注册关联");
                    regeist(phone, sms, password, DeviceId);
                }
                // 用户存在
                if (unRegeisted == 0) {
                    if (!phone.isEmpty() && !"".equals(phone) && !sms.isEmpty() && !"".equals(sms) && !password.isEmpty() && !"".equals(password)) {

                        bundleAndLogin(phone, sms, password, DeviceId);
                    } else {
                        Toast.makeText(getBaseContext(), "手机号码为空或验证码为空或者密码为空", Toast.LENGTH_SHORT).show();
                        return;
                    }
                }

                break;
            //回退到登录窗口
            case R.id.rl_back_login_fromRelation:
                Log.i(TGA,"点击后退");
                startActivity(new Intent(RelationPhoneActivity.this, LoginActivity.class));
                finish();
                break;
        }

    }

    //获取验证码
    private void getVerifyCodeForLogin(final String phone) {
        final android.os.Handler handlerGetSms = new android.os.Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Bundle dataGet = msg.getData();
                int Status = (int) dataGet.get("Status");
                Log.i("info", "Status-->" + Status);
                // 但用户不存在，帮用户注册
                unRegeisted = Status;

            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 创建一个restTemplate 对象
                    ACache mCache = ACache.get(getApplication());

                    // 获取短信验证码,同时绑定取到的sessionKey
                    restTemplate = new RestTemplate();
                    PostSmsCode postSmsCode = new PostSmsCode();
                    postSmsCode.setTelephone(phone);
                    postSmsCode.setVcode("");
                    postSmsCode.setType("login");

                    HttpHeaders requestHL = new HttpHeaders();
                    requestHL.set("Cookie", "JSESSIONID=" + mCache.getAsString("sessionKeyAuth"));
                    requestHL.setContentType(new MediaType("application", "json"));
                    HttpEntity<PostSmsCode> requestEntityAdd = new HttpEntity<>(postSmsCode, requestHL);
                    ResponseEntity<PostSmsCodeResposeStatus> getSms = restTemplate.exchange(URL.CUSTOMER.SEND_SMS, HttpMethod.POST, requestEntityAdd, PostSmsCodeResposeStatus.class);

                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putInt("Status", getSms.getBody().getStatus());
                    msg.setData(bundle);
                    handlerGetSms.handleMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    // 绑定并跳转到登录页面
    private void bundleAndLogin(final String phone, final String sms, final String password, final String DeviceId) {
        final android.os.Handler handlerLogin = new android.os.Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Bundle dataGet = msg.getData();
                if (dataGet.get("Status").equals(1112)) {
                    Intent intentToLogin = new Intent(new Intent(RelationPhoneActivity.this, LoginActivity.class));
                    intentToLogin.setAction("FROM_RELATION_PHONE_ACTIVITY");
                    ArrayList data = new ArrayList<>();
                    PostLoginOauth postLoginOauth = new PostLoginOauth();
                    postLoginOauth.setType(resposeGetPersonInfo.getType());
                    postLoginOauth.setLoginId(resposeGetPersonInfo.getLoginId());
                    postLoginOauth.setAvatar(resposeGetPersonInfo.getAvatar());
                    postLoginOauth.setName(resposeGetPersonInfo.getName());
                    postLoginOauth.setAddress(resposeGetPersonInfo.getAddress());
                    postLoginOauth.setBirthday("");
                    postLoginOauth.setDescription("");
                    postLoginOauth.setGender(resposeGetPersonInfo.getGender());
                    postLoginOauth.setIsActive("");
                    postLoginOauth.setDeviceId(DeviceId);
                    data.add(postLoginOauth);
                    intentToLogin.putCharSequenceArrayListExtra("data", data);
                    startActivity(intentToLogin);
                    finish();
                }

            }


        };
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 创建一个restTemplate 对象
                    ACache mCache = ACache.get(getApplication());
                    // 三方绑定Url
                    // post请求参数
                    PostBundleOauth postBundleOauth = new PostBundleOauth();
                    postBundleOauth.setType(resposeGetPersonInfo.getType());
                    postBundleOauth.setLoginId(resposeGetPersonInfo.getLoginId());
                    postBundleOauth.setAvatar(resposeGetPersonInfo.getAvatar());
                    postBundleOauth.setName(resposeGetPersonInfo.getName());
                    postBundleOauth.setAddress(resposeGetPersonInfo.getAddress());
                    postBundleOauth.setBirthday("");
                    postBundleOauth.setDescription("");
                    postBundleOauth.setGender(resposeGetPersonInfo.getGender());
                    postBundleOauth.setIsActive("");
                    postBundleOauth.setDeviceId(DeviceId);
                    postBundleOauth.setTelephone(phone);
                    postBundleOauth.setPassword(password);
                    postBundleOauth.setSmsCode(sms);
                    // 发起绑定请求
                    HttpHeaders httpHeadersForBundle = new HttpHeaders();
                    httpHeadersForBundle.set("Cookie", "JSESSIONID=" + mCache.getAsString("sessionKeyAuth"));
                    httpHeadersForBundle.setContentType(new MediaType("application", "json"));
                    HttpEntity<PostBundleOauth> requestEntityForBundle = new HttpEntity<>(postBundleOauth, httpHeadersForBundle);
                    ResponseEntity<PostSmsCodeResposeStatus> responseEntityForBundle = restTemplate.exchange(URL.CUSTOMER.BINDING_3RD_PARTY, HttpMethod.POST, requestEntityForBundle, PostSmsCodeResposeStatus.class);

                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putInt("Status", responseEntityForBundle.getBody().getStatus());
                    msg.setData(bundle);
                    handlerLogin.handleMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    // 注册并登录
    private void regeist(final String phone, final String sms, final String password, final String DeviceId) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    // 创建一个restTemplate 对象
                    RestTemplate restTemplate = new RestTemplate();

                    // 取sessionKey
                    ACache mCache = ACache.get(getApplication());
                    String sessionKeyAuth = mCache.getAsString("sessionKeyAuth");
                    Log.i(TGA,"注册绑定session:"+sessionKeyAuth);

                    // 验证手机验证码
                    PostVerfyRegist postVerfy = new PostVerfyRegist();
                    postVerfy.setTelephone(phone);
                    postVerfy.setSmsCode(sms);

                    HttpHeaders requestHL = new HttpHeaders();
                    requestHL.set("Cookie", "JSESSIONID=" + sessionKeyAuth);
                    requestHL.setContentType(new MediaType("application", "json"));
                    HttpEntity<PostVerfyRegist> requestEntityAdd = new HttpEntity<>(postVerfy, requestHL);
                    ResponseEntity<verifyRegistRespose> responseVer = restTemplate.exchange(URL.CUSTOMER.VERIFY_REGISTER, HttpMethod.POST, requestEntityAdd, verifyRegistRespose.class);
                    int statusVerify = responseVer.getBody().getStatus();
                    Log.d("info", "bindle---statusVerify--> " + statusVerify);

                    // 注册
                    PostRegist postRegist = new PostRegist();
                    postRegist.setTelephone(phone);
                    postRegist.setSmsCode(sms);
                    postRegist.setPassword(password);
                    postRegist.setConfirmPassword(password);

                    HttpHeaders requestRegH = new HttpHeaders();
                    requestRegH.set("Cookie", "JSESSIONID=" + sessionKeyAuth);
                    requestRegH.setContentType(new MediaType("application", "json"));
                    HttpEntity<PostRegist> requestEntityReg = new HttpEntity<PostRegist>(postRegist, requestRegH);
                    ResponseEntity<ResposeRegeist> responseRegist = restTemplate.exchange(URL.CUSTOMER.REGISTER, HttpMethod.POST, requestEntityReg, ResposeRegeist.class);
                    // 状态码
                    final int status = responseRegist.getBody().getStatus();
                    Log.d("info", "注册状态==> :" + status);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //注册成功马上绑定登录
                            if (0 == status) {
                                bundleAndLogin(phone, sms, password, DeviceId);
                            }

                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }).start();
    }
}
